package com.cwh.springbootMybatis.httpClientTest;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class NXOAHttpUtil {

	
	public static String doGet(String strUrl) {
		String result = "";
		try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
            	
            	/*http://172.30.135.4:9871/dep/restful/oadoBizTest/OuterAccess_doBiz.do?
            	 * token=5e3f7dea968644130e411d0dc4269141
            	 * &userCode=190298&userName=彭惠珍
            	 * &bizType=CREATE_ZS_GW&serviceType=01
            	 * &billNo=ZFZA_20180149^000fbc2f-d511-41fa-abb9-34c14acf86c0
            	 * &idNumber=null&distCode=640000
            	 * &fileAddress=http://202.1.1.59:8001/NXOA/fileDownload?actionType=DOWNLOAD_FILE&&fileArray=[{"FILE_ID":"1546152610664","BILL_ID":"4fca609d4aef4c1d87e5a382e436293e","FILE_NAME":"新建文本文档.txt","FILE_TYPE":".txt"}]&&preFileName=ZFZA_20180149
            	 * &fileTitle=新建文本文档.txt
            	 * &fileName=新建文本文档.txt
            	 * &fileType=txt
            	 * &recode=[1101]null|[02010101][02010101] 基本养老金支出|222.00元|,null,0.00元
            	 * &audit=吕晓燕|2018-12-30 14:50:15|同意|制单人送审@^彭惠珍|2018-12-30 14:50:59|同意|同意
*/                
            	URL url = new URL(strUrl);
            	System.out.println("doGET=====getProtocol----"+url.getProtocol());
            	System.out.println("doGET=====getHost---"+url.getHost());
            	System.out.println("doGET=====getPort---"+url.getPort());
            	System.out.println("doGET=====getPath----"+url.getPath());
            	System.out.println("doGET=====getQuery-----"+url.getQuery());
            	URI uri = new URI(url.getProtocol(), null, url.getHost(), url.getPort(),  url.getPath(), url.getQuery(), null);
            	System.out.println("uri==========------"+uri.toString());
            	HttpGet httpGet = new HttpGet(uri);

                client = HttpClients.createDefault();
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
        	System.out.println("222222211111------"+result);
            e.printStackTrace();
            return result;
        }
		System.out.println("44444444444------"+result);
		return result;
	}
	
	/**
	 * post请求(用于key-value格式的参数)
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPost(String url, Map params){
		
		BufferedReader in = null;  
        try {  
            // 定义HttpClient  
            HttpClient client = new DefaultHttpClient();  
            // 实例化HTTP方法  
            HttpPost request = new HttpPost();  
            request.setURI(new URI(url));
            
            //设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>(); 
            for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
    			String name = (String) iter.next();
    			String value = String.valueOf(params.get(name));
    			nvps.add(new BasicNameValuePair(name, value));
    			
    			System.out.println(name +"-"+value);
    		}
            request.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
            
            HttpResponse response = client.execute(request);  
            int code = response.getStatusLine().getStatusCode();
            if(code == 200){	//请求成功
            	in = new BufferedReader(new InputStreamReader(response.getEntity()  
                        .getContent(),"utf-8"));
                StringBuffer sb = new StringBuffer("");  
                String line = "";  
                //String NL = System.getProperty("line.separator");  
                while ((line = in.readLine()) != null) {  
                    sb.append(line);  
                }
                in.close();  
                return sb.toString();
            }
            else{	//
            	System.out.println("状态码：" + code);
            	return null;
            }
        }
        catch(Exception e){
        	e.printStackTrace();
        	
        	return null;
        }
	}

	public static String doGet(String strUrl, int timeOut) {
		String result = "";
		try {
			CloseableHttpClient client = null;
			CloseableHttpResponse response = null;
			try {
				URL url = new URL(strUrl);
				System.out.println("doGET=====getProtocol----" + url.getProtocol());
				System.out.println("doGET=====getHost---" + url.getHost());
				System.out.println("doGET=====getPort---" + url.getPort());
				System.out.println("doGET=====getPath----" + url.getPath());
				System.out.println("doGET=====getQuery-----" + url.getQuery());
				URI uri = new URI(url.getProtocol(), null, url.getHost(), url.getPort(), url.getPath(), url.getQuery(), null);
				System.out.println("uri==========------" + uri.toString());
				HttpGet httpGet = new HttpGet(uri);
				RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();//设置请求和传输超时时间
				httpGet.setConfig(requestConfig);
				client = HttpClients.createDefault();
				response = client.execute(httpGet);
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity);
			} finally {
				if (response != null) {
					response.close();
				}
				if (client != null) {
					client.close();
				}
			}
		} catch (Exception e) {
			System.out.println("222222211111------" + result);
			throw new RuntimeException(e);
		}
		System.out.println("44444444444------" + result);
		return result;
	}

	/**
	 * post请求(用于key-value格式的参数)
	 *
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPost(String url, Map params, int timeOut) {

		BufferedReader in = null;
		try {
			// 定义HttpClient
			HttpClient client = new DefaultHttpClient();
			// 实例化HTTP方法
			HttpPost request = new HttpPost();
			request.setURI(new URI(url));
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();//设置请求和传输超时时间
			request.setConfig(requestConfig);
			//设置参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
				String name = (String) iter.next();
				String value = String.valueOf(params.get(name));
				nvps.add(new BasicNameValuePair(name, value));

				System.out.println(name + "-" + value);
			}
			request.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8));
//            request.setHeader("Content-Type","application/json");
			HttpResponse response = client.execute(request);
			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {    //请求成功
				in = new BufferedReader(new InputStreamReader(response.getEntity()
						.getContent(), "utf-8"));
				StringBuffer sb = new StringBuffer("");
				String line = "";
				//String NL = System.getProperty("line.separator");
				while ((line = in.readLine()) != null) {
					sb.append(line);
				}
				in.close();
				return sb.toString();
			} else {    //
				System.out.println("状态码：" + code);
				return null;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
}
